package com.myebills.ebpsfrontend.cust.maxis;

import com.myebills.ebpsfrontend.cust.controller.*;
import com.checkfree.isolutions.customer.persist.*;
import com.checkfree.isolutions.customer.persist.*;
import com.checkfree.isolutions.admin.ObjectId;
import com.checkfree.isolutions.statement.persist.*;
import com.checkfree.isolutions.statement.StatementSection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.checkfree.isolutions.property.Properties;
import com.checkfree.isolutions.property.PropertiesConfig;
import com.checkfree.isolutions.persist.PersistServer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;

import java.util.*;
import java.text.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CusCallTaggingCalculationServlet_v1r00 extends HttpServlet {

    /**
     *
     *
     */

	public void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
		doPost(req, res);
	}

    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException {
        try {

            HttpSession session = req.getSession(false);
            if (null == session) {
                throw new ServletException("Session must be already established");
            }

    		final String randomKey = (String) session.getAttribute(EbppxConstants.RANDOM_KEY);

			PersistServer.activate("Maxis");
			PersistServer.beginTransaction();

            //final EbppxUrlManager urlManager = getUrlManager(req);

	        //Get attribute from session for the logon user
	        final EbppxEcsUser ecsUser = (EbppxEcsUser) session.getAttribute(EbppxConstants.ECS_USER);

            String stmtIndex = req.getParameter("stmtIndex");
            if (stmtIndex.length() == 0) {
                throw new ServletException("Missing statement index");
            }

			stmtIndex =  EncryptionHelper.decrypt(stmtIndex,randomKey);

            final String sOidStatement = req.getParameter(EbppxConstants.STATEMENT_ID);
            if (sOidStatement.length() == 0) {
                throw new ServletException("Missing statement identifier");
            }

            final String sOidAccount   = req.getParameter(EbppxConstants.ACCOUNT_ID);
            if (sOidAccount.length() == 0) {
                throw new ServletException("Missing account identifier");
            }

            final String phoneNo = req.getParameter("phoneNo");
            if (phoneNo.length() == 0) {
                throw new ServletException("Missing phone number");
            }

            final String phoneIndex = req.getParameter("phoneIndex");
            if (phoneIndex.length() == 0) {
                throw new ServletException("Missing phone index");
            }

            final String simNo = req.getParameter("simNo");

            final String fromPage = (String) session.getAttribute("fromPage");

            final Account cfiAccount =  getAccountHome().findById(new ObjectId(EncryptionHelper.decrypt(sOidAccount,randomKey)));

			String callType = "U";
			if(req.getParameter("callType")!=null && !req.getParameter("callType").equals("")){
				callType = req.getParameter("callType");
			}

			Map phoneBookMap = doList(session, ecsUser,callType);

			//////////////////////////////////////////////////////////////////////////////////////
            final Statement cfiStatement = StatementHomeImpl.singleton().findById(new ObjectId(EncryptionHelper.decrypt(sOidStatement,randomKey)));
            final StatementSection cfiRootSection = cfiStatement.getRootSection();
		    StatementSection phoneNumberSection = null;

		    final int intPhoneIndex = Integer.parseInt(phoneIndex);


			    if (cfiRootSection != null){

			        StatementSection cfiSection = cfiRootSection.getSection("DetailsOfChargesSection");
			        if (cfiSection != null){
			            boolean found = false;
			            int sectionCount = (int) cfiSection.getSectionCount("PhoneNumberSection");
			            for (int index = 0; index < sectionCount; index++) {
			                StatementSection cfiRSection0 = cfiSection.getRepeatSection("PhoneNumberSection", index);
			                String str = cfiRSection0.getFieldText("PhoneNumber");


			                if(str.indexOf(":")>=0){
								StringTokenizer st = new StringTokenizer(str,":");
								str = EbppxUtil.nullToEmpty(st.nextToken());
							}

			                if (phoneNo.equals(str) && index==intPhoneIndex){
			                    cfiSection = cfiRSection0;
			                    phoneNumberSection = cfiRSection0;
			                    found = true;
			                    break;
			                }
			            }
			            if (!found){
			                cfiSection = null;
			            }
			        }
				}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
				StatementSection itemsWithRebateSection = phoneNumberSection.getSection("ItemWithRebateSection");
				StatementSection usageChargesSection = itemsWithRebateSection.getSection("UsageChargesSection");

				String keySuffix = "_OTH_Key";

				if(cfiRootSection.getFieldText("MarketSegment").equals("01") || cfiRootSection.getFieldText("MarketSegment").equals("04")){
					// Do some checking on market segment to assign GSM/OTH
					keySuffix = "_GSM_Key";
				}

				if(cfiRootSection.getFieldText("MarketSegment").equals("06")){
					// Do some checking on market segment to assign GSM/OTH
					keySuffix = "_ISP_Key";
				}

				ArrayList phoneBookList = new ArrayList();
				double amount = 0.00;

				if(usageChargesSection!=null){
					int usageChargesSectionCount = (int) usageChargesSection.getSectionCount("RepeatSection");

					for (int j = 0; j < usageChargesSectionCount; j++) {// items in the usages charges section
						StatementSection usageChargesRSection = usageChargesSection.getRepeatSection("RepeatSection", j);
						String item = usageChargesRSection.getFieldText("Item");
						String searchKey = item.replace(' ','_') + keySuffix;

						String key0 = getSectionKey(searchKey);

						if (!key0.equals("")){
							// Do my stuff here
							SectionProperties sp0 = getSectionProperties(key0);
							StatementSection section0 = phoneNumberSection.getSection(sp0.name);

							// For ISP
							if (sp0.type.equals("Type02") && (section0 != null)){
								// Get field text
								int sectionCount = (int)section0.getSectionCount("RepeatSection");

								for (int index = 0; index < sectionCount; index++) {
									StatementSection repeatSection = section0.getRepeatSection("RepeatSection", index);
									ArrayList fieldPropertiesList = getSectionFields(sp0.PBFieldKeyList);

									Iterator iterator = fieldPropertiesList.iterator();

									ArrayList dataList = new ArrayList();
									while (iterator.hasNext()){
										FieldProperties fp = (FieldProperties) iterator.next();
										String fieldData = removeChar(repeatSection.getFieldText(fp.name),',');

										if (fieldData == null){
											fieldData = "";
										}

										dataList.add(fieldData);
									} // end while

									if(phoneBookMap.containsKey(repeatSection.getFieldText("PhoneNumber")) || phoneBookMap.containsKey(repeatSection.getFieldText("NumberCalled"))){
										phoneBookList.add(dataList);
										if(!repeatSection.getFieldText("Total").equals("")){
											amount+=Double.parseDouble(repeatSection.getFieldText("Total"));
										}
									}
								}// end for
							}// end if

							// Type00
							if (sp0.type.equals("Type00") && (section0 != null)){
								Iterator iterator0 = sp0.childSectionKeyList.iterator();

								// While there's more child section
								while (iterator0.hasNext()){
									String key1 = (String)iterator0.next();
									SectionProperties sp1 = getSectionProperties(key1);
									StatementSection section1 = section0.getSection(sp1.name);

									// If there's more section
									if (sp1.type.equals("Type01") && (section1 != null)){
										Iterator iterator1 = sp1.childSectionKeyList.iterator();

										// While's there's more child section
										while (iterator1.hasNext()){
											String key2 = (String)iterator1.next();
											SectionProperties sp2 = getSectionProperties(key2);
											StatementSection section2 = section1.getSection(sp2.name);

											if (sp2.type.equals("Type02") && (section2 != null)){
												// Get field text
												int sectionCount = (int)section2.getSectionCount("RepeatSection");

												for (int index = 0; index < sectionCount; index++) {
													StatementSection repeatSection = section2.getRepeatSection("RepeatSection", index);
													ArrayList fieldPropertiesList = getSectionFields(sp2.PBFieldKeyList);

													Iterator iterator = fieldPropertiesList.iterator();

													ArrayList dataList = new ArrayList();
													while (iterator.hasNext()){
														FieldProperties fp = (FieldProperties) iterator.next();
														String fieldData = removeChar(repeatSection.getFieldText(fp.name),',');

														if (fieldData == null){
															fieldData = "";
														}

														dataList.add(fieldData);

													} // end while
													if(phoneBookMap.containsKey(repeatSection.getFieldText("PhoneNumber")) || phoneBookMap.containsKey(repeatSection.getFieldText("NumberCalled"))){
														phoneBookList.add(dataList);
														if(!repeatSection.getFieldText("Total").equals("")){
															amount+=Double.parseDouble(repeatSection.getFieldText("Total"));
														}
													}
												}// end for
											}// end if
										} // end while
									} // end if there's more section

									// If there's more section
									if (sp1.type.equals("Type05") && (section1 != null)){
										ArrayList sectionNameList = new ArrayList();
										int section1Count = (int) section0.getSectionCount(sp1.name);

										for (int k=0; k<section1Count; k++){
											section1 = section0.getRepeatSection(sp1.name,k);
											String title_ENG = sp1.title_ENG;

											if (sp1.title_ENG.startsWith("*")){
												title_ENG = section1.getFieldText(sp1.title_ENG.substring(1));
											}
											sectionNameList.add(title_ENG);

											Iterator iterator1 = sp1.childSectionKeyList.iterator();

											// While's there's more child section
											while (iterator1.hasNext()){
												String key2 = (String)iterator1.next();
												SectionProperties sp2 = getSectionProperties(key2);
												StatementSection section2 = section1.getSection(sp2.name);

												if (sp2.type.equals("Type02") && (section2 != null)){
													// Get field text
													int sectionCount = (int)section2.getSectionCount("RepeatSection");


													for (int index = 0; index < sectionCount; index++) {
														StatementSection repeatSection = section2.getRepeatSection("RepeatSection", index);
														title_ENG = sp1.title_ENG;
														if (sp1.title_ENG.startsWith("*")){
															title_ENG = section1.getFieldText(sp1.title_ENG.substring(1));
														}

														ArrayList fieldPropertiesList = getSectionFields(sp2.PBFieldKeyList);

														Iterator iterator = fieldPropertiesList.iterator();

														ArrayList dataList = new ArrayList();
														while (iterator.hasNext()){
															FieldProperties fp = (FieldProperties) iterator.next();
															String fieldData = removeChar(repeatSection.getFieldText(fp.name),',');

															if (fieldData == null){
																fieldData = "";
															}

															dataList.add(fieldData);
														} // end while
														if(phoneBookMap.containsKey(repeatSection.getFieldText("PhoneNumber")) || phoneBookMap.containsKey(repeatSection.getFieldText("NumberCalled"))){
															phoneBookList.add(dataList);
															if(!repeatSection.getFieldText("Total").equals("")){
																amount+=Double.parseDouble(repeatSection.getFieldText("Total"));
															}
														}
														//fwFile.write(sp0.title_ENG+"-"+title_ENG+"-"+sp2.title_ENG);
													}// end for
												}// end if
											} // end while
										}// for (int k=0; k<section1Count; k++)
									} // end if there's more section
								}// end While there's more child section

							}else if(sp0.type.equals("Type01") && (section0 != null)){// type 01
								Iterator iterator0 = sp0.childSectionKeyList.iterator();

								// While's there's more child section
								while (iterator0.hasNext()){
									String key1 = (String)iterator0.next();
									SectionProperties sp1 = getSectionProperties(key1);
									StatementSection section1 = section0.getSection(sp1.name);

									if (sp1.type.equals("Type02") && (section1 != null)){
										// Get field text
										int sectionCount = (int)section1.getSectionCount("RepeatSection");


										for (int index = 0; index < sectionCount; index++) {
											StatementSection repeatSection = section1.getRepeatSection("RepeatSection", index);
											ArrayList fieldPropertiesList = getSectionFields(sp1.PBFieldKeyList);

											Iterator iterator = fieldPropertiesList.iterator();

											ArrayList dataList = new ArrayList();
											while (iterator.hasNext()){
												FieldProperties fp = (FieldProperties) iterator.next();
												String fieldData = repeatSection.getFieldText(fp.name);

												if (fieldData == null){
													fieldData = "";
												}

												dataList.add(fieldData);
											}// end while

											if(phoneBookMap.containsKey(repeatSection.getFieldText("PhoneNumber")) || phoneBookMap.containsKey(repeatSection.getFieldText("NumberCalled"))){
												phoneBookList.add(dataList);
												if(!repeatSection.getFieldText("Total").equals("")){
													amount+=Double.parseDouble(repeatSection.getFieldText("Total"));
												}
											}
										}// end for
									}// end if
								} // end while
							}// end type 01
						}// end if key0 not blank
					}// end for items in the usages charges section
				}// if(usageChargesSection!=null)

			// end detail of charges section
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

			// create the requested doc and write to a ByteArrayOutputStream
			ServletOutputStream sos = res.getOutputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

		    CusCallTaggingPDF callTaggingPDF = new CusCallTaggingPDF(phoneNo, cfiAccount.getExternalKey(), phoneBookList,cfiStatement,amount,callType,sos);
		    callTaggingPDF.buildDocument();

			// setting some response headers
			res.setHeader("Expires", "0");
			res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			res.setHeader("Pragma", "public");
			res.setHeader("Content-Disposition", "inline; filename=PhoneCallCalculation.pdf");
			res.setContentType("application/pdf");
			sos.flush();



            /*req.setAttribute(EbppxConstants.CFI_ACCOUNT, cfiAccount);
            req.setAttribute(EbppxConstants.CFI_STATEMENT, cfiStatement);
            req.setAttribute("rootSection", cfiRootSection);
            req.setAttribute("statementSection", cfiRootSection.getSection("DetailsOfChargesSection"));
            req.setAttribute("stmtIndex", stmtIndex);
            req.setAttribute("phoneNo", phoneNo);
            req.setAttribute("phoneIndex", phoneIndex);
            req.setAttribute("simNo", simNo);
            req.setAttribute("fromPage",fromPage);
            req.setAttribute("phoneBookList",phoneBookList);


            session.setAttribute("searchVal1","");
            session.setAttribute("searchVal2","");
            session.setAttribute("searchBy","");
            session.setAttribute("grouped","0");


            forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM);*/
            PersistServer.commitTransaction();
            PersistServer.deactivate();

        } catch (ServletException e) {
            // Just re-throw these
            throw e;
        } catch (Throwable t) {
            throw new ServletException(t.toString(), t);
        }finally{
	        if (PersistServer.transactionIsActive()) {
	            try {
	                PersistServer.rollbackTransaction();

	            } catch (Throwable t) {
	                throw new ServletException(t.toString(), t);
	            }
			}
            PersistServer.deactivate();
		}
    }

    public Map doList(HttpSession session, EbppxEcsUser ecsUser,String callType) throws ServletException {
		Map phoneBookMap = new HashMap();
        try {


                phoneBookMap = PhoneBookDAO.getInstance().list(ecsUser.getUserId(),callType);
                session.setAttribute("PhoneBookMap", phoneBookMap);

            }catch (Throwable t){
                throw new ServletException(t.toString(), t);
            }finally {
	    } //finally
	    return phoneBookMap;
    }

public static String formatAmount(double dblVal) {
  String Amount = "0.00";
    try {
        NumberFormat nf = NumberFormat.getNumberInstance ();
        nf.setMinimumFractionDigits(2);
        nf.setMaximumFractionDigits(2);
        Amount = nf.format(dblVal);
    }catch (Exception e){
    }
  return  Amount;
}

/* MEAU ADD */
public static String removeChar(String s, char c) {
   String r = "";
   for (int i = 0; i < s.length(); i ++) {
      if (s.charAt(i) != c) r += s.charAt(i);
      }
   return r;
   }/*END MEAU ADD */


/**
 *
 */
public static String toTime(int seconds) {
    String time = "00:00:00";
    try {
        int intHour = seconds/3600;
        int intTemp = seconds%3600;
        int intMin = intTemp/60;
        int intSec = intTemp%60;

        String hour = "";
        if (intHour>9)
            hour = Integer.toString(intHour);
        else
            hour = "0"+Integer.toString(intHour);
        String min = "";
        if (intMin>9)
            min = Integer.toString(intMin);
        else
            min = "0"+Integer.toString(intMin);
        String sec = "";
        if (intSec>9)
            sec = Integer.toString(intSec);
        else
            sec = "0"+Integer.toString(intSec);

        time =  hour + ":" + min + ":" + sec;

    }catch (Exception e){
    }

    return time;
}

/**
 *
 */
public static int getSeconds(String time) {
    int seconds = 0;
    try {
        if (!time.equals("")){
            String tempString = "";
            String hour = "";
            String min = "";
            String sec = "";
            int intHour = 0;
            int intMin = 0;
            int intSec = 0;
            int idx = 0;

            tempString = time;
            idx = tempString.indexOf(':');
            hour = tempString.substring(0,idx);
            tempString = tempString.substring(idx+1);
            idx = tempString.indexOf(':');
            min = tempString.substring(0,idx);
            sec = tempString.substring(idx+1);

            intHour = Integer.parseInt(hour)*60*60;
            intMin = Integer.parseInt(min)*60;
            intSec = Integer.parseInt(sec);

            seconds = intHour + intMin + intSec;
        }
    }catch (Exception e){
    }
    return seconds;
}

/**
 *
 */
public class CallDetailsComparator implements Comparator{

  private boolean isAscending = true;
  private int fieldIndex;
  private ArrayList fieldPropertiesList;

  public CallDetailsComparator(boolean isAscending, int fieldIndex, ArrayList fieldPropertiesList) {
      this.isAscending = isAscending;
      this.fieldIndex = fieldIndex;
      this.fieldPropertiesList = fieldPropertiesList;
  }

  public int compare(Object object1, Object object2) {

    try{
        // Cast Objects
        ArrayList list1 = (ArrayList)object1;
        ArrayList list2 = (ArrayList)object2;

        FieldProperties fp = (FieldProperties) fieldPropertiesList.get(fieldIndex);

        String temp1 = (String) list1.get(fieldIndex);
        String temp2 = (String) list2.get(fieldIndex);

        if (fp.type.equals("String")){
            String tmp1 = temp1;
            String tmp2 = temp2;
            if (this.isAscending) {
                return tmp1.compareTo(tmp2);
            } else {
                return -(tmp1.compareTo(tmp2));
            }
        }
        if (fp.type.equals("Double")){
            if (temp1.equals("")){
                temp1 = "0.00";
            }
            if (temp2.equals("")){
                temp2 = "0.00";
            }
            Double tmp1 = new Double(Double.parseDouble(temp1));
            Double tmp2 = new Double(Double.parseDouble(temp2));
            if (this.isAscending) {
                return tmp1.compareTo(tmp2);
            } else {
                return -(tmp1.compareTo(tmp2));
            }
        }
        if (fp.type.equals("Date")){
            DateFormat df = new SimpleDateFormat("dd/MM/yy");
            if (temp1.indexOf("-")>=0){
                temp1 = temp1.substring(0,temp1.indexOf("-")-1);
            }
            if (temp2.indexOf("-")>=0){
                temp2 = temp2.substring(0,temp2.indexOf("-")-1);
            }
            Date tmp1 = df.parse(temp1);
            Date tmp2 = df.parse(temp2);
            if (this.isAscending) {
                return tmp1.compareTo(tmp2);
            } else {
                return -(tmp1.compareTo(tmp2));
            }
        }
        if (fp.type.equals("Time")){
            if (temp1.equals("")){
                temp1 = "00:00:00";
            }
            if (temp2.equals("")){
                temp2 = "00:00:00";
            }
            Integer tmp1 = new Integer(getSeconds(temp1));
            Integer tmp2 = new Integer(getSeconds(temp2));
            if (this.isAscending) {
                return tmp1.compareTo(tmp2);
            } else {
                return -(tmp1.compareTo(tmp2));
            }
        }
    } catch (Exception e){
        return 0;
    }
    return 0;
  }
}

/**
 *
 */
public static class SectionProperties {
    public String key = "";
    public String name = "";
    public String type = "";
    public String title_ENG = "";
    public String title_BM = "";
    public String subTitle_ENG = "";
    public String subTitle_BM = "";

    public ArrayList childSectionKeyList = new ArrayList();
    public ArrayList parentSectionKeyList = new ArrayList();
    public ArrayList fieldKeyList = new ArrayList();
    public ArrayList PBFieldKeyList = new ArrayList();

    public StatementSection section = null;
}

/**
 *
 */
public static class FieldProperties {
    public String key = "";
    public String name = "";
    public String type = "";
    public int width = 0;
    public String title_ENG = "";
    public String title_BM = "";
    public String title_align = "";
    public String data_align = "";
    public int colspan = 0;
    public String phoneBookTag = "N";
}

/**
 *
 */
public static FieldProperties getFieldProperties(String fieldKey) {
    FieldProperties fp = new FieldProperties();

    try {
        Properties appCfg = PropertiesConfig.getApplicationSettings();
        if (appCfg.hasProperty(fieldKey + "_Field")){
            String properties = appCfg.getProperty(fieldKey + "_Field");
            StringTokenizer st = new StringTokenizer((String)properties,"|");
            fp.key = fieldKey;
            if (st.hasMoreTokens()) {
                fp.name = st.nextToken();
            }
            if (st.hasMoreTokens()) {
                fp.type = st.nextToken();
            }
            if (st.hasMoreTokens()) {
                fp.width = Integer.parseInt(st.nextToken());
            }
            if (st.hasMoreTokens()) {
                fp.title_ENG = st.nextToken();
            }
            if (st.hasMoreTokens()) {
                fp.title_BM = st.nextToken();
            }
            if (st.hasMoreTokens()) {
                fp.title_align = st.nextToken();
            }
            if (st.hasMoreTokens()) {
                fp.data_align = st.nextToken();
            }
            if (st.hasMoreTokens()) {
                fp.colspan = Integer.parseInt(st.nextToken());
            }
            if (st.hasMoreTokens()) {
                fp.phoneBookTag = st.nextToken();
            }
        }
    } catch (Exception e){
        // ignore
    }

    return fp;
}

/**
 *
 */
public static ArrayList getSectionFields(ArrayList fieldKeyList){
    ArrayList fpList = new ArrayList();
    try {
        Iterator iterator = fieldKeyList.iterator();
        while (iterator.hasNext()){
            fpList.add(getFieldProperties((String)iterator.next()));
        }
    } catch (Exception e){
        // ignore
    }

    return fpList;
}

/**
 *
 */
public static String getSectionKey(String searchKey) {
    String key = "";

    try {
        Properties appCfg = PropertiesConfig.getApplicationSettings();

        if (appCfg.hasProperty(searchKey)){
            key = appCfg.getProperty(searchKey);
        }
    } catch (Exception e){
        // ignore
    }

    return key;
}

/**
 *
 */
public static SectionProperties getSectionProperties(String key) {
     SectionProperties sp = new SectionProperties();

    try {
        Properties appCfg = PropertiesConfig.getApplicationSettings();
        sp.key = key;
        if (appCfg.hasProperty(key + "_SectionName")){
            sp.name = appCfg.getProperty(key + "_SectionName");
        }
        if (appCfg.hasProperty(key + "_SectionType")){
            sp.type = appCfg.getProperty(key + "_SectionType");
        }
        if (appCfg.hasProperty(key + "_SectionTitle_ENG")){
            sp.title_ENG = appCfg.getProperty(key + "_SectionTitle_ENG");
        }
        if (appCfg.hasProperty(key + "_SectionTitle_BM")){
            sp.title_BM = appCfg.getProperty(key + "_SectionTitle_BM");
        }
        if (appCfg.hasProperty(key + "_SectionSubTitle_ENG")){
            sp.subTitle_ENG = appCfg.getProperty(key + "_SectionSubTitle_ENG");
        }
        if (appCfg.hasProperty(key + "_SectionSubTitle_BM")){
            sp.subTitle_BM = appCfg.getProperty(key + "_SectionSubTitle_BM");
        }
        if (appCfg.hasProperty(key + "_ChildSections")){
            String childSections = appCfg.getProperty(key + "_ChildSections");
            StringTokenizer st = new StringTokenizer((String)childSections,"|");
            while(st.hasMoreTokens()) {
                sp.childSectionKeyList.add(st.nextToken());
            }
        }
        if (appCfg.hasProperty(key + "_Fields")){
            String fields = appCfg.getProperty(key + "_Fields");
            StringTokenizer st = new StringTokenizer((String)fields,"|");
            while(st.hasMoreTokens()) {
                sp.fieldKeyList.add(st.nextToken());
            }
        }
        if (appCfg.hasProperty(key + "_PB_Fields")){
            String fields = appCfg.getProperty(key + "_PB_Fields");
            StringTokenizer st = new StringTokenizer((String)fields,"|");
            while(st.hasMoreTokens()) {
                sp.PBFieldKeyList.add(st.nextToken());
            }
        }
        String parentSections = sp.key;
        StringTokenizer st = new StringTokenizer((String)parentSections,"_");
        String strTemp = "";
        while(st.hasMoreTokens()) {
            strTemp = strTemp + st.nextToken();
            sp.parentSectionKeyList.add(strTemp);
            strTemp = strTemp + "_";
        }
    } catch (Exception e){
        // ignore
    }

    return sp;
}

    protected EbppxUrlManager getUrlManager(
        HttpServletRequest req
    ) throws ServletException {
        final String fName = "getUrlManager";

        EbppxUrlManager mgr = null;
        try {
            mgr = (EbppxUrlManager) req.getAttribute(
                    EbppxUrlManager.REQUEST_ATTRIBUTE_NAME
                );
        } catch (ClassCastException e) {
            mgr = null;
        }
        return mgr;
    }

    /**
     * Convenience method to fetch the AccountHome from the i-Series API.
     *
     * @return  <code>AccountHomeImpl.singleton()</code>
     */
    public AccountHomeImpl getAccountHome() {
        return AccountHomeImpl.singleton();
    }

    /**
     * Convenience method to fetch the StatementHome from the i-Series API.
     *
     * @return  <code>StatementHomeImpl.singleton()</code>
     */
    public StatementHomeImpl getStatementHome() {
        return StatementHomeImpl.singleton();
    }


}
